package com.project.smarthome.common.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by L on 2017/4/7.
 */

public class RespInterceptor implements Interceptor {

    private static Map<String,ResponseHandler> sHandlerMap = new HashMap<>();

    public static void registerResponseHandler(String url,ResponseHandler handler){
        sHandlerMap.put(url,handler);
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());
        if(response.isSuccessful()){
            String url = chain.request().url().toString();
            ResponseHandler responseHandler = sHandlerMap.get(url);
            if(responseHandler!=null){
                try {
                    ResponseBody body = ResponseBody.create(response.body().contentType(), responseHandler.handleResp(response.body().bytes()));
                    sHandlerMap.remove(url);
                    return response.newBuilder().body(body).build();
                }catch (Exception e){
                    return response.newBuilder().code(401).build();
                }
            }
        }
        return response;
    }

    public  interface ResponseHandler{
        byte[] handleResp(byte[] entity);
    }
}
